package com.alax.interfaces.controller;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alax.common.annotation.Log;
import com.alax.common.core.controller.BaseController;
import com.alax.common.core.domain.AjaxResult;
import com.alax.common.core.domain.entity.SysUser;
import com.alax.common.core.domain.model.LoginUser;
import com.alax.common.core.page.TableDataInfo;
import com.alax.common.enums.BusinessType;
import com.alax.common.utils.ApiKeyUtils;
import com.alax.common.utils.SecurityUtils;
import com.alax.interfaces.domain.UserApiKey;
import com.alax.interfaces.service.IUserApiKeyService;

/**
 * 前端API密钥管理Controller
 */
@RestController
@RequestMapping("/front/apikey")
public class FrontApiKeyController extends BaseController {
    @Autowired
    private IUserApiKeyService userApiKeyService;

    /**
     * 获取当前用户的API密钥列表
     */
    @GetMapping("/list")
    public TableDataInfo list() {
        // 获取当前登录用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        
        startPage();
        UserApiKey userApiKey = new UserApiKey();
        userApiKey.setUserId(user.getUserId());
        List<UserApiKey> list = userApiKeyService.selectUserApiKeyList(userApiKey);
        return getDataTable(list);
    }

    /**
     * 获取当前用户的API密钥列表（优化字段）
     */
    @GetMapping("/listOptimized")
    public TableDataInfo listOptimized() {
        // 获取当前登录用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        
        startPage();
        List<UserApiKey> list = userApiKeyService.selectUserApiKeysOptimized(user.getUserId());
        return getDataTable(list);
    }

    /**
     * 生成新的API密钥
     */
    @Log(title = "生成API密钥", businessType = BusinessType.INSERT)
    @PostMapping("/generate")
    public AjaxResult generate(@RequestBody UserApiKey apiKey) {
        // 获取当前登录用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        
        // 生成API密钥对
        String[] keyPair = ApiKeyUtils.generateApiKeyPair();
        
        // 设置API密钥信息
        apiKey.setUserId(user.getUserId());
        apiKey.setApiKey(keyPair[0]);
        apiKey.setApiSecret(keyPair[1]);
        apiKey.setStatus(1); // 默认启用状态
        
        // 如果没有设置过期时间，默认一年后过期
        if (apiKey.getExpireTime() == null) {
            apiKey.setExpireTime(new Date(System.currentTimeMillis() + 365 * 24 * 60 * 60 * 1000L));
        }
        
        // 如果没有设置调用限制，默认值
        if (apiKey.getDailyLimit() == null) {
            apiKey.setDailyLimit(10000L);
        }
        
        if (apiKey.getQpsLimit() == null) {
            apiKey.setQpsLimit(10L);
        }
        
        apiKey.setCreateBy(user.getUserName());
        
        userApiKeyService.insertUserApiKey(apiKey);
        return AjaxResult.success(apiKey);
    }

    /**
     * 更新API密钥状态
     */
    @Log(title = "更新API密钥状态", businessType = BusinessType.UPDATE)
    @PutMapping("/status")
    public AjaxResult updateStatus(@RequestBody UserApiKey apiKey) {
        // 获取当前登录用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        
        // 确保只能修改自己的API密钥
        UserApiKey existApiKey = userApiKeyService.selectUserApiKeyById(apiKey.getId());
        if (existApiKey == null || !existApiKey.getUserId().equals(user.getUserId())) {
            return AjaxResult.error("无权操作此API密钥");
        }
        
        // 只更新状态
        UserApiKey updateApiKey = new UserApiKey();
        updateApiKey.setId(apiKey.getId());
        updateApiKey.setStatus(apiKey.getStatus());
        updateApiKey.setUpdateBy(user.getUserName());
        
        userApiKeyService.updateUserApiKey(updateApiKey);
        return AjaxResult.success();
    }

    /**
     * 删除API密钥
     */
    @Log(title = "删除API密钥", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable Long id) {
        // 获取当前登录用户
        LoginUser loginUser = SecurityUtils.getLoginUser();
        SysUser user = loginUser.getUser();
        
        // 确保只能删除自己的API密钥
        UserApiKey apiKey = userApiKeyService.selectUserApiKeyById(id);
        if (apiKey == null || !apiKey.getUserId().equals(user.getUserId())) {
            return AjaxResult.error("无权操作此API密钥");
        }
        
        return toAjax(userApiKeyService.deleteUserApiKeyById(id));
    }
} 